package com.finley.flowabledemo.controller;


import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部署成功，部署 ID：9e915597-3bcb-11f0-bbe3-7ef5bb99a67e
 * 流程启动成功，流程实例 ID：f72a9cb2-3bcb-11f0-8f25-7ef5bb99a67e
 */
@RestController
@RequestMapping("/process")
public class ProcessController {

    @Autowired
    private RepositoryService repositoryService; // 流程定义相关服务

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    /**
     *
     * @param param day: 请假天数, studentUser: 请假人
     * @return
     */
    @PostMapping("/start")
    public ResponseEntity startProcess(@RequestBody Map<String, Object> param) {
        // 员工提交请假申请
        Map<String, Object> map = new HashMap<>();
        map.put("day", param.get("day"));
        map.put("studentUser", param.get("studentUser"));
        // leave为员工请假流程xml文件中的id
        ProcessInstance a1 = runtimeService.startProcessInstanceByKey("leave", map);

        Task task = taskService.createTaskQuery().processInstanceId(a1.getId()).singleResult();
        taskService.complete(task.getId());
        return ResponseEntity.ok("processid:" + a1.getId());
    }

    /**
     *
     * @param group 领导对应的组信息: a:经理, b:老板
     * @return
     */
    @GetMapping("/order_list")
    public List<Task> getTasks(@RequestParam String group) {
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup(group).orderByTaskCreateTime().desc().list();
        for (Task task : tasks) {
            // 根据任务id查询当前任务参数
            Map<String, Object> variables = taskService.getVariables(task.getId());
            System.out.println(variables.get("day") + "," + variables.get("studentUser"));
        }
        return tasks;
    }

    /**
     * 领导审批
     * @param group 领导对应的组信息: a:经理, b:老板
     * @param outcome 审批结果: 通过, 驳回
     * @return
     */
    @PutMapping("/approval")
    public ResponseEntity LeadApprovalTask(@RequestParam String group,
                                           @RequestParam String outcome) {
        // 领导审批
        List<Task> teacherTaskList = taskService.createTaskQuery().taskCandidateGroup(group).list();
        Map<String, Object> teacherMap = new HashMap<>();
        teacherMap.put("outcome", outcome);
        for (Task teacherTask : teacherTaskList) {
            taskService.complete(teacherTask.getId(), teacherMap);
        }
        return ResponseEntity.ok("success");
    }


    /**
     *
     * @return
     */
    @GetMapping("/queryHistory")
    public ResponseEntity queryHistory() {
        List<ProcessInstance> processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("leave").orderByStartTime().desc().list();
        if (CollectionUtils.isEmpty(processInstance)) {
            System.out.println("------------------------------------------");
        }
        // 获取最近的一个流程
        List<HistoricActivityInstance> activities = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstance.get(0).getId())
                // 只查询已经完成的活动
                .finished()
                // 按照结束时间排序
                .orderByHistoricActivityInstanceEndTime().desc()
                .list();
        List<String> collect = activities.stream().map(a -> "活动名称:" + a.getActivityName() + ";活动执行时间:" + a.getDurationInMillis() + "毫秒").collect(Collectors.toList());
        for (String s : collect) {
            System.out.println(s);

        }
        return ResponseEntity.ok("success");
    }

    @GetMapping("/processDigram/{processId}")
    public void getDigram(@PathVariable String processId) {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (Objects.isNull(pi)) {
            return;
        }

        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).list();
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution execution : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(execution.getId());
            activityIds.addAll(ids);
        }



    }


        @PostMapping("/complete")
    public String completeTask(@RequestParam String taskId, @RequestParam Map<String, Object> variables) {
        taskService.complete(taskId, variables); // 完成任务时可以传递变量，比如审批意见
        return "任务完成，流程继续";
    }


    @Autowired
    private HistoryService historyService;

    @GetMapping("/history")
    public void queryHistoryTasks(@RequestParam String processInstanceId) {
        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceStartTime().asc()
                .list();
        for (HistoricTaskInstance task : tasks) {
            System.out.println("任务名称：" + task.getName() + "，负责人：" + task.getAssignee() + "，状态：" + task.getCategory());
        }
    }


}
